#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

int main() {
    // 创建 Socket
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1) {
        std::cerr << "Failed to create socket!" << std::endl;
        return -1;
    }

    // 设置服务器地址
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);

    // 发送数据
    const char* message = "Hello from UDP client!";
    sendto(sock, message, strlen(message), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));

    // 接收响应
    char buffer[1024] = {0};
    struct sockaddr_in from_addr;
    socklen_t from_len = sizeof(from_addr);
    recvfrom(sock, buffer, 1024, 0, (struct sockaddr*)&from_addr, &from_len);
    std::cout << "Server response: " << buffer << std::endl;

    close(sock);
    return 0;
}